<?php

namespace mpend\modules\dynamic\models;

use common\logics\DynamicLogic;
use common\models\dynamic\Dynamic;
use common\models\dynamic\Topic;
use Yii;
use yii\data\ActiveDataProvider;
use common\models\dynamic\DynamicTopic;
use yii\db\Exception;

/**
 * This is the model class for table "{{%dynamic_topic}}".
 *
 * @property int $id
 * @property string $topic_content 话题内容
 * @property int $topic_id 话题id
 * @property int $dynamic_id 动态id
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class DynamicTopicSearch extends DynamicLogic {

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params = []) {
        $condition = [];
        if (isset($params['topic_id'])) {
            $condition['topic_id'] = $params['topic_id'];
        } else if (isset($params['topic_content'])) {
            $condition['topic_content'] = trim($params['topic_content'], '#');
        } else{
            throw new Exception('参数topic_content , topic_id 必须有一个存在 ');
        }


        $dynamicTopics = DynamicTopic::find()->where(['or', $condition])->asArray()->all();

        $query = static::find()->where([
            'status' => static::STATUS_ACTIVE,
            'deleted_at' => 0,
            'id' => array_column($dynamicTopics,'dynamic_id')
        ]);
        $query->with(['user', 'stats', 'gallery']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        Yii::$app->db->cache(function ($db) use ($dataProvider) {
            $dataProvider->prepare();
        }, 60);

        return $dataProvider;
    }

    public function getPublishTime() {
        return $this->created_at;
    }

}
